var _this;
var app = new Vue({
    el: '#app',
    data: function () {
        return {
            itemData: [],// 项目列表信息
            projectId: '', // 项目ID
            itemDialogVisible: false, // 项目信息弹框
            itemInfo: {},// 项目信息
            evcDialogVisible: false, //  生成源码 显示 隐藏
            evcInfo: {}, // 生成源码信息
            evcType: '', // 下载源码 类型

            schemas: [],
            schema: {
                genParam: {
                    packageName: "com.king",//包名
                    moduleName: "test",//模块名
                    tablePrefix: "tb_",//表格前缀
                    genToPath: "",//生成路径
                    author: "king",//作者
                    email: "136499160@qq.com",//邮箱
                    version: "1.0"//版本号
                },
                tableName: "",
                tableDesc: "",
                pageable: true,
                formLayout: "FORM",
                listLayout: "LIST",

                tableFields: [],
                tableOperates: [],
                extendedFields: []
            },
            //defaultFields: [],
            defaultOperates: [],
            //defaultOperateMapping: {},
            fieldTypes: [], // 字段类型
            fieldTypeMapping: {},
            widgetTypes: [], // 表单展示
            widgetTypeMapping: {},
            filterTypes: [],// 列表过滤
            filterTypeMapping: {},
            relationTypes: [],
            relationTypeMapping: {},
            validateTypes: [],
            validateTypeMapping: {},
            pkStrategyTypes: [],
            pkStrategyTypeMapping: {},
            listLayouts: [],
            formLayouts: [],

            listPageTotal: 0, //  数据总数量
            listPageSize: 11, // 每页数量
            listPageNo: 1, // 页数
            searchValue: '', // 搜索内容

            operatorDialogVisible: false,// 添加操作的弹出框
            operateForm: {}, // 新增的操作按钮
            extendedOperates: [],
            formShow: false, // zoom 显示

            tablesAndFields: [], // 关联表字段

            allowListLayout: [],//表单

            menuKey: 1,

            exprotShow: false,// 是否显示导出那一列
            addFieldType: true, //添加字段类型
            mergeArr: [], // 合并后的数组
            popover: '', //键值对下标
            defaultSelect: [], // 操作选择的值

            rules: {
                tableName: [
                    {required: true, message: '请输入表名', trigger: 'blur'},
                ],
                tableDesc: [
                    {required: true, message: '请输入表说明', trigger: 'blur'},
                ],
                pkStrategy: [
                    {required: true, message: '请选择主键策略', trigger: 'blur'},
                ],
                relationType: [
                    {required: true, message: '请选择表类型', trigger: 'blur'},
                ],
                formLayout: [
                    {required: true, message: '请选择表单布局', trigger: 'blur'},
                ],
                name: [
                    {required: true, message: '请选择表单布局', trigger: 'blur'},
                ],

                // 项目信息
                projectName: [
                    {required: true, message: '请输入项目名称', trigger: 'blur'},
                ],
                packageName: [
                    {required: true, message: '请输入包名', trigger: 'blur'},
                ],
                moduleName: [
                    {required: true, message: '请输入模块名称', trigger: 'blur'},
                ],
                tablePrefix: [
                    {required: true, message: '请输入表格前缀', trigger: 'blur'},
                ],
                genToPath: [
                    {required: true, message: '请输入代码生成路径', trigger: 'blur'},
                ],
                auth: [
                    {required: true, message: '请输入作者', trigger: 'blur'},
                ],
                email: [
                    {required: true, message: '请输入作者邮箱', trigger: 'blur'},
                ],
                version: [
                    {required: true, message: '请输入版本号', trigger: 'blur'},
                ],

                genToPath: [
                    {required: true, message: '请输入路径', trigger: 'blur'},
                ],
            }
        }
    },
    created: function () {
        _this = this;
        this.initItem();
        //this.initEnums("defaultField");

    },
    computed: {
        tableExportable() {
            return this.schema && this.schema.tableOperates && this.schema.tableFields;
        }
    },
    watch: {
        schema: function () {
            console.log(this.schema)
        }
    },
    methods: {
        initItem() { // 项目初始化
            this.initEnums("defaultOperate");
            this.initEnums("fieldType");
            this.initEnums("widgetType");
            this.initEnums("filterType");
            this.initEnums("relationType");
            this.initEnums("validateType");
            this.initEnums("pkStrategyType");
            this.initEnums("listLayout");
            this.initEnums("formLayout");

            this.itemList();
        },
        initGenTableFromDb() {
            axios.get("/generator/dbtable/list").then(r => {
                console.info(r)

            })
        },
        saveEvcInfo: function () {  // 开始下载源码
            var data = this.$refs.multipleTable.selection;
            var tableIds = [];
            for (var i = 0; i < data.length; i++) {
                tableIds.push(data[i].tableId);
            }
            tableIds = tableIds.join(",");
            var url = '/generator/batchGenCode2Zip?tableIds=' + tableIds;
            if (this.evcType == 'path') {
                if (!this.evcInfo.genToPath) {
                    this.$message.error('请填写路径');
                    return;
                }
                url = '/generator/batchGenCode2Path?tableIds=' + tableIds;
            }
            if (this.evcType == 'path') {
                axios.post(url, this.evcInfo)
                    .then(response => {
                        console.log(response);
                        _this.evcDialogVisible = false;

                    }).catch(function (error) {
                    console.log(error);
                });
            } else {
                axios.post(url, this.evcInfo, {responseType: 'blob'})
                    .then(response => {
                        let blob = new Blob([response.data]);
                        let downloadElement = document.createElement('a');
                        let href = window.URL.createObjectURL(blob); //创建下载的链接
                        downloadElement.href = href;
                        downloadElement.download = '用户数据.zip'; //下载后文件名
                        document.body.appendChild(downloadElement);
                        downloadElement.click(); //点击下载
                        document.body.removeChild(downloadElement); //下载完成移除元素
                        window.URL.revokeObjectURL(href); //释放掉blob对象

                        _this.evcDialogVisible = false;

                    }).catch(function (error) {
                    console.log(error);
                });
            }


        },
        goEvc: function (type) { // 下载源码  （包含指定目录）
            var data = this.$refs.multipleTable.selection;
            if (data.length == 0) {
                this.$message.error('请先选择表');
                return;
            }
            this.evcDialogVisible = true;
            if (type) {
                this.evcType = type;
                this.evcInfo.genToPath = '';
            } else {
                this.evcType = '';
            }
        },
        itemList: function (pageNo) { // 项目列表
            if (!pageNo) {
                this.listPageNo = 1;
            }
            axios.get("/project/page?page=" + this.listPageNo + '&limit=9999').then(r => {
                if (r.data.data.list.length > 0) {
                    this.projectId = r.data.data.list[0].projectId;
                }
                console.log(this.projectId)
                this.evcInfo = r.data.data.list[0];
                this.itemData = r.data.data.list;
                this.listPageTotal = r.data.data.totalCount;
                this.itemInEnums(r.data.data.list[0]);

            })
        },
        addItem: function () { // 新增项目
            this.projectId = '';
            this.itemInfo = {};
            this.itemDialogVisible = true;
        },
        itemInfoDetails: function (projectId) { // 根据项目id查询信息
            axios.get("/project/info/" + projectId).then(r => {
                this.itemInfo = r.data.data;
                this.itemDialogVisible = true;
            })
        },
        saveItemInfo: function () { // 新增 修改 项目信息
            var url = "/project/add";
            if (this.projectId) {
                url = "/project/edit";
            }
            axios.post(url, this.itemInfo).then(r => {
                this.initItem();
                this.itemDialogVisible = false;
            })
        },
        itemInEnums: function (scope) { // 查看项目里面表的初始化
            var projectId = scope.projectId;
            this.evcInfo = scope;
            this.projectId = projectId;
            this.initAllTablesAndFields();
            this.tableList();
        },
        initEnums(type) { // 表单  初始化 
            axios.get("/generator/enums?type=" + type).then(r => {
                this[type + "s"] = r.data.data;
                console.info(type + "s", this[type + "s"]);

                if (this[type + "Mapping"]) {
                    const mapping = {};
                    let list = r.data.data;
                    for (let i = 0; i < list.length; i++) {
                        mapping[list[i]["name"]] = list[i];
                    }
                    console.info(type + "Mapping", mapping);
                    this[type + "Mapping"] = mapping;
                }
            })
        },
        tableList: function (pageNo) { // 表单列表
            if (!pageNo) {
                this.listPageNo = 1;
            }
            axios.get("/table/page?projectId=" + this.projectId + "&page=" + this.listPageNo + '&limit=' + this.listPageSize).then(r => {
                this.schemas = r.data.data.list;
                this.listPageTotal = r.data.data.totalCount;
            })
        },
        initAllTablesAndFields() {
            var projectId = this.projectId;
            var url = "/table/project-tables/" + projectId;
            axios.get(url).then(r => {
                console.info("rr", r);
                let tables = r.data.tables;
                this.schemas = tables;
                console.info("tables ", tables);
                let tablesAndFields = [];
                for (let i = 0; i < tables.length; i++) {
                    let tmp = tables[i];
                    let table = {};
                    table.label = tmp.tableDesc;
                    table.value = tmp.tableName;
                    let fields = [];
                    for (let j = 0; j < tmp.tableFields.length; j++) {
                        let tmpField = tmp.tableFields[j];
                        let field = {};
                        field.label = tmpField.desc;
                        field.value = tmpField.name;
                        fields.push(field)
                    }
                    table.children = fields;
                    tablesAndFields.push(table)
                }
                this.tablesAndFields = tablesAndFields;
            })
        },
        selectRelation(val, type) { // 选择表类型
            let obj = {};
            obj = this.relationTypes.find((item) => {
                return item.name === val;//筛选出匹配数据
            });

            this.schema.tableFields = obj.defaultFields;
            for (var i = 0; i < this.schema.tableFields.length; i++) {
                if (!type) {
                    this.schema.tableFields[i].unique = false;
                    this.schema.tableFields[i].pk = false;
                    this.schema.tableFields[i].nullable = true;
                    this.schema.tableFields[i].listViewable = true;
                    this.schema.tableFields[i].sortable = false;
                    this.schema.tableFields[i].exportable = false;
                    this.schema.tableFields[i].required = false;
                    this.schema.tableFields[i].enums = []; // 键值对

                    this.schema.tableFields[i].isExtendField = false; // 是否是扩展字段
                }
            }

            if (this.schema.extendedFields.length > 0) {
                for (var i = 0; i < this.schema.extendedFields.length; i++) {
                    this.schema.extendedFields[i].isExtendField = true;
                }
            }

            this.mergeArr = this.schema.tableFields.concat(this.schema.extendedFields);
            for (var i = 0; i < this.mergeArr.length; i++) {
                if (this.mergeArr[i].ref) {
                    var tableName = this.mergeArr[i].ref['tableName'];
                    var fieldName = this.mergeArr[i].ref['fieldName'];
                    this.mergeArr[i].ref = [tableName, fieldName];
                }
            }

            this.allowListLayout = obj.allowListLayout;
            this.schema.listLayout = obj.allowListLayout[0].name;

            ++this.menuKey
        },
        handelUpdate: function (type, val) { // 重新渲染  switch
            ++this.menuKey
        },
        closeCheckbox: function (index) { // 删除新增按钮
            this.extendedOperates.splice(index, 1);
        },
        addExtendedOperates: function () { // 新增按钮
            if (this.operateForm.length > 0) {
                for (var i = 0; i < this.operateForm.length; i++) {
                    if (this.operateForm[i].name == this.operateForm.name) {
                        this.$message.error('操作名称不能相同')
                        return;
                    }
                }
            }
            if (!this.operateForm.batchable) {
                this.operateForm.batchable = false;
            }
            if (!this.operateForm.singleable) {
                this.operateForm.singleable = false;
            }
            this.extendedOperates.push(this.operateForm);
            this.operatorDialogVisible = false;
            this.operateForm = {};
        },
        deleteTr: function (index) { // 表格删除一行
            this.mergeArr.splice(index, 1);
        },
        handleCheckedCitiesChange: function (type) { // 操作选中
            if (type == 'EXPROT') {
                this.exprotShow = !this.exprotShow;
            }
        },
        addKeyValue: function (index) { // 添加键值对
            if (this.mergeArr[index].widgetType == 'Switch') {
                if (this.mergeArr[index].enums.length >= 2) {
                    this.$message.error('最多只能添加两个');
                    return;
                }
            }
            this.mergeArr[index].enums.push({
                name: '',
                val: '',
                desc: '',
            })
        },
        selectWidgetType: function (index, val) { // 选择表单展示
            this.mergeArr[index].enums = [];
            if (!val) {

            }
        },
        popoverShow: function (index) { // 键值对显示时  获取哪一行
            this.popover = index;
        },
        deleteKeyVal: function (index) {// 删除键值对
            this.mergeArr[this.popover].enums.splice(index, 1);
        },

        addOrEdit: function (tableId) { // 新增 修改表
            if (tableId) {
                axios.get('/table/info/' + tableId + '?projectId=' + this.projectId).then(res => {
                    this.schema = res.data.data;
                    console.log(this.schema.tableFields[0].ref)
                    this.selectRelation(res.data.data.relationType, 'edit');
                    this.formShow = true;
                })
                return
            }
            this.schema = {
                tableName: "",
                tableDesc: "",
                pageable: true,
                formLayout: "FORM",
                listLayout: "LIST",

                tableFields: [],
                tableOperates: [],
                extendedFields: []
            }
            this.formShow = true;
        },
        search: function () { // 查询
            if (this.searchValue) {

            }
        },
        addOrEditField: function (type) { // 添加修改字段
            var object = {
                unique: false,
                pk: false,
                nullable: true,
                listViewable: true,
                sortable: false,
                exportable: false,
                required: false,
                enums: [],
            };
            let index = 0;
            for (let i = 0; i < this.mergeArr.length; i++) {
                if (this.mergeArr[i].isExtendField) {
                    index++;
                }
            }
            if (type === 'addNew') {
                this.addFieldType = true;
                object.isExtendField = false;
                if (index === 0) {
                    this.mergeArr.push(object);
                } else {
                    this.mergeArr.splice(this.mergeArr.length - index, 0, object);
                }
            } else if (type === 'extend') {
                this.addFieldType = false;
                object.isExtendField = true;
                this.mergeArr.push(object)
            }
        },
        itemTableRowClassName: function (row) {
            if (row.row.projectId == this.projectId) {
                return 'extendFieldBg'
            }
        },
        tableRowClassName: function (row) { // 扩展字段加背景颜色
            if (row.row.isExtendField) {
                return 'extendFieldBg'
            }
        },
        saveData: function (schema) { // 保存
            for (let i = 0; i < this.mergeArr.length; i++) {
                if (this.mergeArr[i].ref) {
                    let tableName = this.mergeArr[i].ref[0];
                    let fieldName = this.mergeArr[i].ref[1];
                    this.mergeArr[i].ref = {};
                    this.mergeArr[i].ref['tableName'] = tableName;
                    this.mergeArr[i].ref['fieldName'] = fieldName;
                }
            }
            this.mergeArrSplit();
            this.setTableOperates();
            this.schema.projectId = this.projectId;

            this.$refs[schema].validate((valid) => {
                if (!valid) {
                    // TODO 给出提示信息
                    return;
                }
                axios.post('/table/add', this.schema).then(res => {
                    _this.$message.success('保存成功');
                    _this.formShow = false;
                    _this.tableList();
                })
            });
        },
        mergeArrSplit: function () { //拆分数组
            var tableFields = [];
            var extendedFields = [];
            for (var i = 0; i < this.mergeArr.length; i++) {
                if (this.mergeArr[i].isExtendField) {
                    extendedFields.push(this.mergeArr[i]);
                } else {
                    tableFields.push(this.mergeArr[i]);
                }
            }
            this.schema.extendedFields = extendedFields;
            this.schema.tableFields = tableFields;

        },
        setTableOperates() { // 设置 选择的操作
            var arr = [];
            var select = this.defaultOperates.concat(this.extendedOperates);
            for (var i = 0; i < select.length; i++) {
                for (var j = 0; j < this.defaultSelect.length; j++) {
                    if (select[i].desc == this.defaultSelect[j]) {
                        arr.push(select[i])
                    }
                }
            }
            this.schema.tableOperates = arr;
        },
        closeZoom: function () { // 关闭 表格信息
            this.formShow = false;
        },
        handleSizeChange(val) {
            this.listPageNo = 1;
            this.tableList(this.listPageNo);
        },
        handleCurrentChange(val) {
            this.listPageNo = val;
            this.tableList(this.listPageNo);
        },
        // 调转到关联表字段的设置页面
        toRelationFieldPage(field) {
            console.info(field);
        }
    }
})